# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description分类视图
"""
from flask import request
from api.models import Category
from api.category import category_api, category_blue
from api.utils.response import to_response
from api.utils.baseResource import BaseResource
from api import db
from api.utils.tokens import login_required
from api.utils.utils import get_tree


class CategoryResource(BaseResource):

    def get(self):
        id = request.args.get('id', None)
        if not id:
            return to_response(status=10000)
        try:
            category = Category.query.get(id)
        except Exception as e:
            return to_response(status=10020)

        if not category:
            return to_response(status=10017)

        return to_response(200, data=category.to_dict())

    def post(self):
        name = request.json.get('name') if request.json.get('name') else None
        level = request.json.get('level') if request.json.get('level') else None
        pid = request.json.get('pid') if request.json.get('pid') else None

        if not all([name, level]):
            return to_response(status=10000)
        if not Category.query.filter(Category.id == int(pid)).first():
            return to_response(status=10017)
        try:
            category = Category(name=name, level=level, pid=pid)
            db.session.add(category)
            db.session.commit()
            return to_response(200, data=category.to_dict(), msg='添加成功！')
        except Exception as e:
            print(e)
            return to_response(status=10020)

    def put(self):
        id = request.json.get('id', None)
        name = request.json.get('name', None)
        level = request.json.get('level', None)
        pid = request.json.get('pid', None)
        if not all([id, name]):
            return to_response(status=10000)
        try:
            category = Category.query.get(id)
        except Exception as e:
            return to_response(status=10020)

        if not category:
            return to_response(status=10017)

        try:
            category.name = name
            category.level = level
            category.pid = pid
            db.session.commit()
            return to_response(200, data=category.to_dict(), msg='修改成功！')
        except Exception as e:
            return to_response(status=10020)

    def delete(self):
        id = request.args.get('id', None)
        if not id:
            return to_response(status=10000)
        try:
            category = Category.query.get(id)
        except Exception as e:
            return to_response(status=10020)
        if not category:
            return to_response(status=10017)

        try:
            db.session.delete(category)
            db.session.commit()
            return to_response(200, msg='删除成功！')
        except Exception as e:
            return to_response(status=10020)


category_api.add_resource(CategoryResource, '/category')


@category_blue.route('/category_list')
@login_required
def get_category_list():
    level = int(request.args.get('level')) if request.args.get('level') and int(request.args.get('level')) <= 3 else 0
    page = request.args.get('page') if request.args.get('page') else 0
    psize = request.args.get('psize') if request.args.get('psize') else 0
    cate_list = []
    base_query = Category.query.filter(Category.level == 1)

    if all([page, psize]):
        categories = base_query.paginate(page=int(page), per_page=int(psize))
        if level:
            cate_list = get_tree(categories.items, level, True)
        else:
            cate_list = get_tree(categories.items, level, False)

        data = {
            'page': page,
            'pages': psize,
            'total': categories.total,
            'data': cate_list
        }
        return to_response(200, data=data, msg='获取列表成功！')
    else:
        categories = base_query.all()
        if level:
            cate_list = get_tree(categories, level, True)
        else:
            cate_list = get_tree(categories, level, False)

        return to_response(200, data=cate_list, msg='获取列表成功！')


from sqlalchemy import func


@category_blue.route('/cate_group_level')
@login_required
def get_cate_group_level():
    group_data = db.session.query(Category.level, func.count(1).label('count')).group_by(Category.level)
    data = {
        'name': '数量',
        'xAxis': [f'{g[0]}级分类' for g in group_data],
        'series': [g[1] for g in group_data]
    }
    return to_response(200, data=data, msg='获取列表成功！')
